<template>
  <div class="model-panel-body">
    <!-- 条件栏 -->
    <PageFilter
      v-model:query="filterInfo.query"
      :filter-list="filterInfo.list"
      :listTypeInfo="listTypeInfo"
    >
      <template v-slot:filter-setPrintQty>
        <el-button :disabled="!tableInfo.selections.length" @click="setPrintQty"
          >设置最大打印数量</el-button
        >
      </template>
      <template v-slot:filter-print>
        <el-button :disabled="!tableInfo.selections.length" @click="printQrCode"
          >打印二维码</el-button
        >
      </template>
<!--      <template v-slot:filter-fill>-->
<!--        <el-checkbox-->
<!--          v-model="fill"-->
<!--          label="否库存为0"-->
<!--          border-->
<!--          @change="changeCheck"-->
<!--        ></el-checkbox>-->
<!--    </template>-->
    </PageFilter>
    <!-- 表格 -->
    <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
      <PageTable
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="getCurrentDepotStoragePage"
        :tabIndex="true"
        v-model:query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :summary="false"
        :mergeData="tableInfo.mergeData"
        :mergeFiled="tableInfo.mergeFiled"
        :reserveSelection="true"
        :handle="tableInfo.handle"
        :isDynamic="true"
        @handleEvent="handleEvent"
        ref="multipleTable"
      >
        <template v-slot:col-licenseNumber="scope">
          <p>{{ scope.row.licenseNumber || '-' }}</p>
          <p>{{ scope.row.brandName || '-' }}</p>
        </template>
        <template v-slot:col-commonName="scope">
          <p>{{ scope.row.commonName || '-' }}</p>
          <p>{{ scope.row.productCode || '-' }}</p>
          <p>{{ scope.row.alias || '-' }}</p>
        </template>
        <template v-slot:col-type="scope">
          <p>{{ scope.row.productTypeValue || '-' }}</p>
          <p>{{ scope.row.codeTypeValue || '-' }}</p>
          <p>{{ scope.row.productCategoryValue || '-' }}</p>
        </template>
        <template v-slot:col-standard="scope">
          <p>{{ scope.row.standard || '-' }}</p>
          <p>{{ scope.row.unitName || '-' }}</p>
        </template>
        <template v-slot:col-printQty="scope">
          <el-form-item
            v-if="scope.row.codeType === 1 || scope.row.codeType === 4"
            :prop="`data.${scope.$index}.printQty`"
            :rules="
              scope.$index >= 0
                ? [
                    {
                      validator: $validate.naturalnumber,
                      trigger: 'blur,change',
                    },
                  ]
                : []
            "
          >
            <el-input-number
              v-model="scope.row.printQty"
              :precision="0"
              :min="1"
              :max="maxPrintQty(scope.row)"
              @change="changePringQty(scope.row)"
              controls-position="right"
            ></el-input-number>
          </el-form-item>
          <span v-else>
            {{ scope.row.printQty }}
          </span>
        </template>
      </PageTable>
    </el-form>
    <IndividualDetails
      v-if="showIndividualDetails"
      v-model:show-dialog="showIndividualDetails"
      v-model:query="paramsIndividual"
      :info="productInfo"
      @handlePrintQRcode="onPrintQRcode"
    ></IndividualDetails>
    <!-- @callback="onIndividualTableInfoDatails" -->
    <ChosePrinter
      v-model:visible="printerInfo.visible"
      @callBack="handlePrinterCallBack"
    />
  </div>
</template>

<script setup name="ReplenishPrintQRcode">
import { getCurrentDepotStoragePage } from '@/api/stock'
import { getDepotAll, printQrCodeReprint } from '@/api/core'
import IndividualDetails from './IndividualDetails'
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const listTypeInfo = ref({
  depotList: [],
})
const printerInfo = ref({
  visible: false,
  data: {},
})
const fill = ref(false)
// 过滤相关配置
const filterInfo = ref({
  query: {
    sort: 'product_id desc',
    searchType: 'product',
    searchField: 'productId',
    enabledDepotAuth: 'depotId',
    stockQtyGreater: '0',
    differentPriceMult: true,
    needPrintType: 'system',
    greaterThanZero: ''
  },
  list: [
    {
      type: 'slip-select',
      label: '仓库',
      value: 'depotId',
      api: getDepotAll,
      query: {
        depotAuth: 'id',
        useTypeId: '1',
        status: '1',
      },
      event: search,
    },
    {
      type: 'search',
      label: '名称/别名/编码/助记符搜索',
      value: 'keyword',
      event: search,
    },
    {
      type: 'search',
      label: '输入个体码搜索',
      value: 'unityCode',
      event: search,
    },
    {
      type: 'slot',
      value: 'setPrintQty',
    },
    {
      type: 'slot',
      value: 'print',
    },
    // {
    //   type: 'slot',
    //   value: 'fill'
    // }
    // { type: "button", label: "搜索", event: search }
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  maxArr: [],
  selections: [],
  summaryFieldList: [
    { value: 'stockQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumPrice', formatter: proxy.$fn.TripartiteMethod },
    { value: 'frozenQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'pendStockQty', formatter: proxy.$fn.qtyFormatter },
  ],
  mergeFiled: ['commonName', 'type', 'standard', 'licenseNumber'],
  mergeData: {},
  fieldList: [
    {
      label: '通用名称\n编码\n别名',
      value: 'commonName',
      type: 'slot',
      minWidth: '220px',
    },
    {
      label: '产品类型\n条码类型\n产品分类',
      value: 'type',
      type: 'slot',
      minWidth: '150px',
    },
    { label: '规格\n计量单位', value: 'standard', type: 'slot' },
    { label: '生产批号', value: 'batchNumber' },
    { label: '生产日期', value: 'productionDate' },
    { label: '失效日期', value: 'validityDate' },
    {
      label: '库存数量',
      value: 'qty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    { label: '打印数量', value: 'printQty', type: 'slot', minWidth: '160px' },
    {
      label: '证号\n生产厂家',
      value: 'licenseNumber',
      type: 'slot',
      minWidth: '220px',
    },
  ],
  singleProductDialog: {
    visible: false,
    query: {},
  },
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '个体详情',
        event: singleProductDetails,
        show: true,
      },
    ],
  },
})
const showIndividualDetails = ref(false)
const paramsIndividual = ref({})
const productInfo = ref({})

watch(
  () => tableInfo.value.data,
  (val) => {
    tableInfo.value.mergeData = proxy.$fn.getMergeData(val)
  },
  { deep: true }
)
// function changeCheck(){
//   filterInfo.value.query.greaterThanZero = fill.value ? '1' : ''
//   search()
// }
function singleProductDetails(row) {
  const data = {
    depotAuth: 'depotId',
    idIn: row.groupConcatIds,
  }
  if (!row.selections) row.selections = []
  productInfo.value = row
  paramsIndividual.value = data
  showIndividualDetails.value = true
}
function changePringQty(row) {
  if (tableInfo.value.selections.length) {
    tableInfo.value.selections.forEach((item) => {
      if (item.id === row.id) {
        item.printQty = row.printQty
      }
    })
  }
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
function onPrintQRcode(selections) {
  let params = []
  selections.forEach((item) => {
    params.push({
      id: item.id,
      qty: item.printQty,
    })
  })
  printQrCodeReprint(params).then((res) => {
    if (res && res.success) {
      printerInfo.value.visible = true
      printerInfo.value.data = res.data
    }
  })
}
// function onIndividualTableInfoDatails(data) {
//   tableInfo.value.data.map((item) => {
//     if (
//       item.productId === data.table.productId &&
//       item.validityDate === data.table.validityDate &&
//       item.batchNumber === data.table.batchNumber &&
//       item.productionDate === data.table.productionDate
//     ) {
//       item.selections = data.selections

//       proxy.$refs['multipleTable'].toggleRowSelection(
//         item,
//         !!data.selections.length
//       )

//       return item
//     }
//   })
// }
function setPrintQty() {
  tableInfo.value.selections.forEach((item) => {
    tableInfo.value.data.forEach((el) => {
      if (el.id === item.id) {
        item.printQty = Math.ceil(item.qty)
        el.printQty = item.printQty
      }
    })
  })
  proxy.$nextTick(() => {
    proxy.$refs.tableForm.clearValidate()
  })
}
function maxPrintQty(row) {
  let qty = row.qty ? row.qty : 1
  return Math.ceil(qty)
}
function printQrCode() {
  let selections = tableInfo.value.selections
  let items = selections.filter((item) => !item.printQty)
  if (items.length) {
    proxy.$message({
      type: 'warning',
      duration: 3500,
      message: '当前所勾选的产品存在打印数量为空的情况，请处理',
      showClose: true,
    })
    return
  }
  let params = []
  selections.forEach((item) => {
    if (item.codeType === 2 || item.codeType === 3) {
      let arr = proxy.$fn.splitArr(item.groupConcatIds)
      arr.forEach((el) => {
        params.push({
          id: el,
          qty: 1,
        })
      })
    } else {
      params.push({
        id: item.id,
        qty: item.printQty,
      })
    }
  })
  printQrCodeReprint(params).then((res) => {
    if (res && res.success) {
      printerInfo.value.visible = true
      printerInfo.value.data = res.data
    }
  })
}
function handlePrinterCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.value.data, printer)
  }
  printerInfo.value.visible = false
}
// 搜索
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
// 触发事件
function handleEvent(event, data) {
  let arr = []
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = data
      // emits('callback', tableInfo.value)
      break
    case 'list':
      data.forEach((item) => {
        item.printQty =
          item.codeType === 2 || item.codeType === 3 ? Math.ceil(item.qty) : 1
        if (tableInfo.value.selections.length) {
          tableInfo.value.selections.forEach((el) => {
            if (el.id === item.id) {
              item.printQty = el.printQty
            }
          })
        }
      })
      tableInfo.value.data = data
      break
  }
}

onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
:deep(.page-table) > .el-table {
  overflow: hidden;
}
</style>
